<template>
  <el-dialog
      title="填入老人近期信息"
      v-model="state.visible"
      width="450px"
  >
    <el-form :model="state.ruleForm" :rules="state.rules" ref="formRef" label-width="100px" class="good-form">

      <el-form-item label="身高(cm)" prop="height">
        <el-input-number
            v-model="state.ruleForm.height"
            :min="50"
            :max="250"
            :precision="1"
            controls-position="right"
        />
      </el-form-item>
      <el-form-item label="体重(kg)" prop="weight">
        <el-input-number
            v-model="state.ruleForm.weight"
            :min="10"
            :max="300"
            :precision="1"
            controls-position="right"
        />
      </el-form-item>

      <el-form-item label="血压(mmHg)" prop="bloodPressure">
        <el-input
            v-model="state.ruleForm.bloodPressure"
            placeholder="格式：120/80"
        />
      </el-form-item>

      <el-form-item label="既往病史" prop="medicalHistory">
        <el-input
            type="textarea"
            v-model="state.ruleForm.medicalHistory"
            placeholder="请输入既往病史"
        />
      </el-form-item>

      <el-form-item label="不适状况" prop="discomfort">
        <el-input
            type="textarea"
            v-model="state.ruleForm.discomfort"
            placeholder="请输入当前不适症状"
        />
      </el-form-item>

      <el-form-item label="睡眠质量" prop="sleepQuality">
        <el-select
            v-model="state.ruleForm.sleepQuality"
            placeholder="请选择"
            clearable
        >
          <el-option label="良好" value="良好"/>
          <el-option label="一般" value="一般"/>
          <el-option label="较差" value="较差"/>
          <el-option label="失眠" value="失眠"/>
        </el-select>
      </el-form-item>

      <el-form-item label="是否抽烟" prop="isSmoking">
        <el-select
            v-model="state.ruleForm.isSmoking"
            placeholder="请选择"
            clearable
        >
          <el-option label="是" value="是"/>
          <el-option label="否" value="否"/>
        </el-select>
      </el-form-item>

      <el-form-item label="是否喝酒" prop="isDrinking">
        <el-select
            v-model="state.ruleForm.isDrinking"
            placeholder="请选择"
            clearable
        >
          <el-option label="是" value="是"/>
          <el-option label="否" value="否"/>
        </el-select>
      </el-form-item>
      <el-form-item label="收集人邮箱" prop="recipientEmail">
        <el-input
            type="text"
            v-model="state.ruleForm.recipientEmail"
            :precision="1"
            placeholder="结果将发到你的邮箱"
        />
      </el-form-item>
      <p>*预测结果由颐养智策AI分析生成，仅供参考，如若需要请根据实际情况去医院就诊。</p>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">生成结果</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {reactive, ref} from 'vue'
import {useRoute} from 'vue-router'
import {ClientAddElderly, ClientUpdateElderly, ClientgetElderlyInfoById} from '../../service/elderlyInfoApi.js'

import {ElMessage, ElMessageBox} from 'element-plus'
import {sendHealthReport} from "../../service/deepseekApi.js";

const props = defineProps({
  reload: Function // 添加或修改完后，刷新列表页
})
const formRef = ref(null)
const route = useRoute()
const state = reactive({
  visible: false,
  parentId: 0,
  ruleForm: {
    elderlyName: '',    // 老人姓名
    age: '',            // 年龄
    gender: '',         // 性别
    address: '',        // 地址
    height: '',         // 身高
    weight: '',         // 体重
    bloodPressure: '',  // 血压
    medicalHistory: '', // 病史
    discomfort: '',     // 不适状况
    sleepQuality: '',   // 睡眠质量
    isSmoking: '',      // 是否抽烟
    isDrinking: '',     // 是否喝酒
    recipientEmail: '', // 收件人邮箱
  },
  rules: {

    height: [
      {type: 'number', message: '身高必须为数字值', trigger: 'blur'},
      {required: true, message: '请输入身高', trigger: 'blur'}
    ],
    weight: [
      {type: 'number', message: '体重必须为数字值', trigger: 'blur'},
      {required: true, message: '请输入体重', trigger: 'blur'}
    ],
    recipientEmail: [
      {required: true, message: '请输入收件人邮箱', trigger: 'blur'}
    ],

  },
})

// 开启弹窗
const open = (id) => {
  state.visible = true
  if (id) {
    // 先查询老人默认信息
    ClientgetElderlyInfoById(id).then((res) => {
      state.ruleForm = {
        elderlyName: res.data.elderlyName,  // 老人姓名
        age: res.data.age,                  // 年龄
        gender: res.data.gender,            // 性别
        address: res.data.address,          // 地址
        height: '',                         // 身高
        weight: '',                         // 体重
        bloodPressure: '',                  // 血压
        medicalHistory: '',                 // 病史
        discomfort: '',                     // 不适状况
        sleepQuality: '',                   // 睡眠质量
        isSmoking: '',                      // 是否抽烟
        isDrinking: '',                     // 是否喝酒
        recipientEmail: '',                 // 收件人邮箱
      }
    })
  } else {
    state.ruleForm = {
      elderlyName: '',    // 老人姓名
      age: '',            // 年龄
      gender: '',         // 性别
      address: '',        // 地址
      height: '',         // 身高
      weight: '',         // 体重
      bloodPressure: '',  // 血压
      medicalHistory: '', // 病史
      discomfort: '',     // 不适状况
      sleepQuality: '',   // 睡眠质量
      isSmoking: '',      // 是否抽烟
      isDrinking: '',     // 是否喝酒
      recipientEmail: '', // 收件人邮箱
    }
  }

}
// 关闭弹窗
const close = () => {
  state.visible = false
}
const submitForm = async () => {
  try {
    // 第一步：表单验证
    await formRef.value.validate(); // 确保基础验证通过

    // 第二步：邮箱格式验证
    const email = state.ruleForm.recipientEmail;
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (!emailRegex.test(email)) {
      ElMessage.error('邮箱格式不正确，请输入类似 example@example.com 的格式');
      return;
    }

    // 第三步：确认弹窗
    const confirm = await ElMessageBox.confirm(
        `您填写的邮箱是：${email}<br>确认提交吗？`,
        '提交确认',
        {
          confirmButtonText: '确认提交',
          cancelButtonText: '重新填写',
          type: 'warning',
          dangerouslyUseHTMLString: true // 允许HTML内容
        }
    );

    if (confirm === 'confirm') {
      ElMessage.success(`数据已提交，颐养智策AI正在分析处理，预计将在1分钟内发送至 ${email}`);
      close();
      props.reload?.();
      // 提交数据
      await sendHealthReport(state.ruleForm);
    }
  } catch (error) {
    // 捕获所有异常（包括API错误、验证失败等）
    if (error?.code === 'validate') {
      ElMessage.error('请先完成必填字段');
    } else {
      ElMessage.error('提交失败，请检查输入或网络连接');
      console.error('提交表单时发生错误:', error);
    }
  }
}


defineExpose({open, close})
</script>

<style scoped>

</style>